library(httr)
library(jsonlite)
library(tidyverse)
library(glue)
library(lubridate)
# Step 1: get the key
key <- "736d25b09ea7a1a2bfaf1a0eb6fd8381"
latitude <- -36.8535
longitude <- 174.7656
# Step 2: find the url and endpoint
api_url <- "https://api.darksky.net"
api_endpoint <- "/forecast/{key}/{latitude},{longitude}"
# Step 3: convert input to JSON: skipped
# Step 4: send the request
response <- GET(url=api_url, path=glue(api_endpoint))
if (response$status_code != 200){
stop(paste("GET failed",response$status_code))
}
response
## Response [https://api.darksky.net/forecast/736d25b09ea7a1a2bfaf1a0eb6fd8381/-36.8535,174.7656]
## Date: 2019-07-12 13:21
## Status: 200
## Content-Type: application/json; charset=utf-8
## Size: 24.9 kB
## {"latitude":-36.8535,"longitude":174.7656,"timezone":"Pacific/Auckland",...
# Step 5: extract the results from response
fcast <- response %>%
content() %>%
reshape2::melt() %>%
filter(L1=='hourly', L2=='data') %>%
spread(L4,value) %>%
select(-L1,-L2,-L3) %>%
as_tibble() %>%
mutate(time = as_datetime(as.numeric(time))) %>%
mutate_if(is.character,as.numeric) %>%
select(time, everything())
fcast
# Next steps: use the data in analysis e.g. plotting, merging, modelling etc
ggplot(fcast)+
geom_line(aes(time,temperature))
response <- GET(url = api_url, path = glue(api_endpoint), query = list(units = "si"))
if (response$status_code != 200){
stop(paste("GET failed",response$status_code))
}
fcast <- response %>%
content() %>%
reshape2::melt() %>%
filter(L1=='hourly', L2=='data') %>%
spread(L4,value) %>%
select(-L1,-L2,-L3) %>%
as_tibble() %>%
mutate(time = as_datetime(as.numeric(time))) %>%
mutate_if(is.character,as.numeric) %>%
select(time, everything())
ggplot(fcast)+
geom_line(aes(time,temperature))
plt <- fcast %>%
gather(key = "attribute", value = "measurement", -time) %>%
ggplot() +
geom_line(aes(x=time, y=measurement, group=attribute, color=attribute))
plt
## Warning: Removed 4 rows containing missing values (geom_path).
library(plotly)
ggplotly(plt)
create config.yml file in the project directory with following contents, learn more about config R library here
config.yml
default:
dark_sky_api_key: 736d25b09ea7a1a2bfaf1a0eb6fd8381
now use config R library to read/load the API key, this way your code is independent from the key file and can be shared with peers or collaborators
config <- config::get()
key <- config$dark_sky_api_key
library(darksky)
# set DarkSky API Key
Sys.setenv(DARKSKY_API_KEY= config$dark_sky_api_key)
now <- get_current_forecast(43.2672, -70.8617)
plot(now)
start_dt <- today()
## Warning in system("timedatectl", intern = TRUE): running command
## 'timedatectl' had status 1
end_dt <- start_dt + days(3)
weather_si <- seq(start_dt, end_dt, "1 day") %>%
map(~darksky::get_forecast_for(latitude, longitude, .x, units="si")) %>%
map_df("hourly")
weather_si %>%
ggplot(aes(x=time, y=temperature)) +
geom_line()
# unset DarkSky API Key
Sys.unsetenv("DARKSKY_API_KEY")